<?php

/*
 * 生成树类（递归）
 */
 
class Tree extends Base {
	
	//生成树需要的二维数组，必须提供id, fid两个字段
	protected $id_name = 'id';
	
	protected $fid_name = 'fid';
	
	protected $list = array();
	
	//生成的tree数组
	protected $tree = array();
	
	protected $_valid = array(
		'id_name',
		'fid_name',
		'list'
	);
	
	public function __construct($config = array())
	{
		if ($config)
		{
			$this->config($config);
		}
	}
	
	/*
	 * 初始化
	 * @access	public
	 * @return	boolean
	 */
	public function init()
	{
		foreach ($this->list as $row)
		{
			if (isset($row[$this->id_name]) && isset($row[$this->fid_name]))
			{
				$this->set_error('生成树提供的结果集错误！');
				return FALSE;
			}
		}
		
		return TRUE;
	}

	/*
	 * 返回根为id的数结果
	 * @access	public
	 * @param	$id integer 节点id
	 * @return	array
	 */
	public function get($id = 0)
	{
		$this->build_node($this->find_root());
		return $this->tree;
	}
	
	/*
	 * 寻找根节点id
	 * access protected
	 * return integer
	 */
	protected function find_root()
	{
		$root = -1;
		if ($this->list)
		{
			foreach ($this->list as $row)
			{
				if ($root == -1 || $root > $row[$this->fid_name])
				{
					$root = $row[$this->fid_name];
				}
			}
		}
		return $root;
	}
	
	/*
	 * 得到子节点数组
	 * @access	protected
	 * @param	$id integer 节点id
	 * @return	array
	 */
	protected function get_childs($id)
	{	
		$childs = array();
		foreach ($this->list as $k => $v)
		{
			if($v[$this->fid_name] == $id)
			{
				$childs[] = $v;
				unset($this->list[$k]);
			}
		}
		return $childs;
	}
	
	/*
	 * 递归节点
	 * @access	protected
	 * @param	$id integer 父节点id
	 * @return	void
	 */
	protected function build_node($id = 0, $level = 1)
	{
		$childs = $this->get_childs($id);
		
		if ($childs)
		{
			foreach ($childs as &$child)
			{
				$child['level'] = $level;
				$this->tree[] = $child;
				//递归的建立树结果集
				$this->build_node($child[$this->id_name], $level + 1);
			}
		}
	}

}